/**
 * Copyright (C) 2017 Fuzhou Rockchip Electronics Co., Ltd
 * author: hertz.wang hertz.wong@rock-chips.com
 *
 * This software is licensed under the terms of the GNU General Public
 * License version 2, as published by the Free Software Foundation, and
 * may be copied, distributed, and modified under those terms.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#ifndef SCALEENCODETSHANDLER_H
#define SCALEENCODETSHANDLER_H

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/time.h>
}

#include "scale_encode_handler.h"
#include "encoder_muxing/encoder/mpp_h264_encoder.h"
#include "encoder_muxing/encoder/ffmpeg_wrapper/ff_context.h"

#define SCALED_WIDTH 1280//640
#define SCALED_HEIGHT 720//384
#define SCALED_BIT_RATE 1500000//800000

class ScaleEncodeTSHandler : public ScaleEncodeHandler<MPPH264Encoder>
{
public:
    ScaleEncodeTSHandler(MediaConfig& config);
    virtual ~ScaleEncodeTSHandler();
    int Init(MediaConfig src_config);
    virtual void DeInit() override;
    void Process(int src_fd, const VideoConfig& src_config, const timeval& time);
    int StartTransferStream(char* uri, pthread_attr_t* global_attr);
    int StopTransferStream();

protected:
    char format[16];
    virtual void GetSrcConfig(const MediaConfig& src_config,
                              int& src_w,
                              int& src_h,
                              PixelFormat& src_fmt) final;
    virtual int PrepareBuffers(MediaConfig& src_config,
                               const int dst_numerator,
                               const int dst_denominator,
                               int& dst_w,
                               int& dst_h) override;
    virtual void Work() final;

private:
    enum { ENTER, RUNNING, PAUSING, EXIT };
    char spspps[64];
    int spspps_len;    
    volatile int state_;
    char *strMediaBuf;
    AVFormatContext* oc;
    MediaConfig scale_config_;  // bit_rate, gop, width, height
    struct timeval time_val_;
    FFContext ff_ctx_;  // ffmpeg muxer help context
    int get_spspps(AVFormatContext* oc, char *spspps, int *len);
};

#endif  // SCALEENCODETSHANDLER_H
